package com.gupao.javavip.netty.push.server.processor.handler;

import com.gupao.javavip.netty.push.api.*;
import com.gupao.javavip.netty.push.server.processor.PushMsgServerService;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.apachecommons.CommonsLog;

@CommonsLog
public class ReceiveMsgServerHandler extends SimpleChannelInboundHandler<Request> {
    private PushMsgServerService service = new PushMsgServerService();

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Request request) throws Exception {
        if (!RequestCommand.RECEIVE.name().equals(request.getCommand())) {
            channelHandlerContext.fireChannelRead(request);
            return;
        }

        log.info("获取" + request.getPushSource() + "的推送消息：" + request.toString());

        PushMsg msg = service.getMsg(request.getPushSource());

        sendResponse(channelHandlerContext, msg);
    }

    private void sendResponse(ChannelHandlerContext channelHandlerContext, PushMsg msg) {
        Response response = new Response();
        response.setCode(ResponseCode.SUCCESS.name());

        if (msg != null) {
            response.setPushMsg(msg);
            response.setMsg("获取到一条最新的推送消息！");
        } else {
            response.setMsg("未获取到最新的推送消息...");
        }

        channelHandlerContext.channel().writeAndFlush(response).addListener((ChannelFuture writeFuture) -> {
            //消息发送成功
            if (writeFuture.isSuccess()) {
                if (msg == null) {
                    log.info("消息应答成功！");
                } else {
                    log.info("消息[" + msg.getId() + "]推送成功！");
                }
            }
            //消息发送失败
            else {
                log.error("消息[" + msg.getId() + "]推送失败...");
            }
        });
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.warn("与客户端断开连接:" + cause.getMessage(), cause);
        ctx.close();
    }
}
